//
//  ISTakePhotoSettingViewController.m
//  iPhoneSafety
//
//  Created by dl on 2019/1/5.
//  Copyright © 2019 com.li.ding. All rights reserved.
//

#import "ISTakePhotoSettingViewController.h"
#import "ISSafetyAlarmMailManager.h"
#import "UIView+BlocksKit.h"
#import "UIControl+BlocksKit.h"
#import "ISPickerView.h"
#import <AVFoundation/AVFoundation.h>

NSString * const kISSafetyAlarmMailSendType = @"kISSafetyAlarmMailSendType";

@interface ISTakePhotoSettingViewController ()
@property (nonatomic, strong) UILabel *tipLabel;
@property (nonatomic, strong) UIImageView *tipImageView;

@property (nonatomic, strong) UIView *actionsContentView;

@property (nonatomic, strong) UILabel *switchTitleLabel;
@property (nonatomic, strong) UISwitch *switchBtn;

@property (nonatomic, strong) UIView *mailContentView;
@property (nonatomic, strong) UILabel *mailTitleLabel;
@property (nonatomic, strong) UILabel *mailAddressLabel;
@property (nonatomic, strong) UIImageView *mailRightArrow;

@property (nonatomic, strong) UIView *triggerContentView;
@property (nonatomic, strong) UILabel *triggerModeTitleLabel;
@property (nonatomic, strong) UILabel *triggerModeLabel;
@property (nonatomic, strong) UIImageView *triggerRightArrow;

@property (nonatomic, strong) ISPickerView *pickerView;
@property (nonatomic, strong) NSArray *pickerData;
@end

@implementation ISTakePhotoSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"防盗抓拍";
    
    self.pickerData = @[
                        @{@"obj": @0, @"title": @"立即抓拍"},
                        @{@"obj": @1, @"title": @"密码错误1次"},
                        @{@"obj": @2, @"title": @"密码错误2次"},
                        @{@"obj": @3, @"title": @"密码错误3次"},
                        @{@"obj": @4, @"title": @"密码错误4次"}
                        ];
    
    [self.view addSubview:self.tipLabel];
    [self.view addSubview:self.tipImageView];
    [self.tipImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.tipLabel.mas_bottom);
        make.height.equalTo(self.tipImageView.mas_width).multipliedBy(270.f / 375.f);
    }];
    
    [self.view addSubview:self.actionsContentView];
    [self.actionsContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.bottom.equalTo(self.view);
        make.top.equalTo(self.tipImageView.mas_bottom);
    }];
    
    [self.actionsContentView addSubview:self.switchTitleLabel];
    [self.actionsContentView addSubview:self.switchBtn];
    [self.switchTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@18.f);
        make.height.equalTo(@70.f);
    }];
    [self.switchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(@-16.f);
        make.centerY.equalTo(self.switchTitleLabel);
    }];
    
    [self.actionsContentView addSubview:self.mailContentView];
    [self.mailContentView addSubview:self.mailTitleLabel];
    [self.mailContentView addSubview:self.mailAddressLabel];
    [self.mailContentView addSubview:self.mailRightArrow];
    [self.mailContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.equalTo(self.actionsContentView);
        make.height.equalTo(@70.f);
        make.top.equalTo(self.switchTitleLabel.mas_bottom);
    }];
    [self.mailTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@18.f);
        make.centerY.equalTo(self.mailContentView);
    }];
    [self.mailRightArrow mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(@-16.f);
        make.centerY.equalTo(self.mailTitleLabel);
        make.size.mas_equalTo(CGSizeMake(17.f, 17.f));
    }];
    [self.mailAddressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.mailRightArrow.mas_left).offset(-5.f);
        make.centerY.equalTo(self.mailRightArrow);
    }];
    
    [self.actionsContentView addSubview:self.triggerContentView];
    [self.triggerContentView addSubview:self.triggerModeTitleLabel];
    [self.triggerContentView addSubview:self.triggerModeLabel];
    [self.triggerContentView addSubview:self.triggerRightArrow];
    [self.triggerContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mailContentView.mas_bottom);
        make.width.right.equalTo(self.actionsContentView);
        make.height.equalTo(@70.f);
    }];
    [self.triggerModeTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@18.f);
        make.centerY.equalTo(self.triggerContentView);
    }];
    [self.triggerRightArrow mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(@-16.f);
        make.centerY.equalTo(self.triggerModeTitleLabel);
        make.size.mas_equalTo(CGSizeMake(17.f, 17.f));
    }];
    [self.triggerModeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.triggerRightArrow.mas_left).offset(-5.f);
        make.centerY.equalTo(self.triggerModeTitleLabel);
    }];
    
    self.mailAddressLabel.text = [ISSafetyAlarmMailManager sharedInstance].receiver ?: @"未设置";
    
    NSInteger triggerType = [[[NSUserDefaults standardUserDefaults] valueForKey:kISSafetyAlarmMailSendType] integerValue];
    self.triggerModeLabel.text = [self.pickerData bk_select:^BOOL(id obj) {
        return [obj[@"obj"] integerValue] == triggerType;
    }].firstObject[@"title"];
    
    @weakify(self)
    [self.switchBtn bk_addEventHandler:^(id sender) {
        @strongify(self)
        if (self.switchBtn.on && [self.mailAddressLabel.text isEqualToString:@"未设置"]) {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.switchBtn.on = NO;
                    [self showMailInputAlert];
                });
            }];
            return ;
        }
        [[ISSafetyAlarmMailManager sharedInstance] enableTakePhoto:self.switchBtn.on];
    } forControlEvents:UIControlEventTouchUpInside];
    
    [self.mailContentView bk_whenTapped:^{
        @strongify(self)
        [self showMailInputAlert];
    }];
    
    [self.triggerContentView bk_whenTapped:^{
        @strongify(self)
        NSNumber *value = [[NSUserDefaults standardUserDefaults] valueForKey:kISSafetyAlarmMailSendType];
        [self.pickerView showWithList:self.pickerData selectIdx:[[self.pickerData bk_select:^BOOL(id obj) {
            return [obj[@"obj"] isEqual:value];
        }].firstObject[@"obj"] integerValue]];
    }];
}

- (void) showMailInputAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请输入您的安全邮箱" message:@"输错密码后拍照的图片将发送到该邮箱" preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = [ISSafetyAlarmMailManager sharedInstance].receiver ?: @"";
        textField.placeholder = @"请输入安全邮箱";
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString *receiver = alert.textFields.firstObject.text;
        if ([NSString nw_isEmptyString:receiver]) {
            [NWToast showToast:@"请输入邮箱"];
            return ;
        }
        [[ISSafetyAlarmMailManager sharedInstance] updateReceiver:alert.textFields.firstObject.text];
        self.mailAddressLabel.text = [ISSafetyAlarmMailManager sharedInstance].receiver ?: @"未设置";
    }];
    [alert addAction:cancelAction];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    if (@available(iOS 11.0, *)) {
        self.tipLabel.frame = CGRectMake(0.f, self.view.safeAreaInsets.top, self.view.width, 105.f);
    } else {
        self.tipLabel.frame = CGRectMake(0.f, 0.f, self.view.width, 105.f);
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
    self.navigationController.navigationBar.titleTextAttributes = @{
                                                                    NSForegroundColorAttributeName:[UIColor blackColor],
                                                                    NSFontAttributeName: [UIFont nw_systemFontOfSize:18 weight:NWFontWeightMedium]
                                                                    };
}

#pragma mark - getters
NWLazyPropertyWithInit(UILabel, tipLabel, {
    _tipLabel.backgroundColor = [UIColor nw_colorWithHex:0xEBEFF2];
    _tipLabel.textAlignment = NSTextAlignmentCenter;
    _tipLabel.numberOfLines = 0.f;
    _tipLabel.font = [UIFont systemFontOfSize:18];
    _tipLabel.textColor = [UIColor nw_colorWithHex:0x222222];
})
NWLazyPropertyWithInit(UIImageView, tipImageView, {
    _tipImageView.image = [UIImage imageNamed:@"img_setting_pic_photo"];
    _tipImageView.contentMode = UIViewContentModeScaleAspectFit;
    _tipImageView.backgroundColor = [UIColor nw_colorWithHex:0xEBEFF2];
})
NWLazyPropertyWithInit(UIView, actionsContentView, {
    _actionsContentView.backgroundColor = [UIColor whiteColor];
})
NWLazyPropertyWithInit(UILabel, switchTitleLabel, {
    _switchTitleLabel.font = [UIFont systemFontOfSize:17];
    _switchTitleLabel.textColor = [UIColor nw_colorWithHex:0x222222];
    _switchTitleLabel.text = @"开启";
})
NWLazyPropertyWithInit(UISwitch, switchBtn, {
    _switchBtn.onTintColor = [UIColor nw_colorWithHex:0x0084FF];
    _switchBtn.tintColor = [UIColor nw_colorWithHex:0xCDD8E2];
    _switchBtn.backgroundColor = [UIColor nw_colorWithHex:0xCDD8E2];
    _switchBtn.clipsToBounds = YES;
    _switchBtn.layer.cornerRadius = CGRectGetHeight(_switchBtn.frame) / 2.f;
})
NWLazyPropertyWithInit(UIView, mailContentView, {})
NWLazyPropertyWithInit(UILabel, mailTitleLabel, {
    _mailTitleLabel.font = [UIFont systemFontOfSize:17];
    _mailTitleLabel.textColor = [UIColor nw_colorWithHex:0x222222];
    _mailTitleLabel.text = @"接收邮箱";
})
NWLazyPropertyWithInit(UILabel, mailAddressLabel, {
    _mailAddressLabel.font = [UIFont systemFontOfSize:14];
    _mailAddressLabel.textColor = [UIColor nw_colorWithHex:0xA6ADB7];
    _mailAddressLabel.textAlignment = NSTextAlignmentRight;
    _mailAddressLabel.text = @"未设置";
})
NWLazyPropertyWithInit(UIImageView, mailRightArrow, {
    _mailRightArrow.image = [UIImage imageNamed:@"btn_rightarrow_n"];
})
NWLazyPropertyWithInit(UIView, triggerContentView, {})
NWLazyPropertyWithInit(UILabel, triggerModeTitleLabel, {
    _triggerModeTitleLabel.font = [UIFont systemFontOfSize:17];
    _triggerModeTitleLabel.textColor = [UIColor nw_colorWithHex:0x222222];
    _triggerModeTitleLabel.text = @"触发方式";
})
NWLazyPropertyWithInit(UILabel, triggerModeLabel, {
    _triggerModeLabel.font = [UIFont systemFontOfSize:14];
    _triggerModeLabel.textColor = [UIColor nw_colorWithHex:0xA6ADB7];
    _triggerModeLabel.textAlignment = NSTextAlignmentRight;
    _triggerModeLabel.text = @"立即抓拍";
})
NWLazyPropertyWithInit(UIImageView, triggerRightArrow, {
    _triggerRightArrow.image = [UIImage imageNamed:@"btn_rightarrow_n"];
})

NWLazyPropertyWithInit(ISPickerView, pickerView, {
    _pickerView.selectBlock = ^(id item, NSInteger row) {};
    @weakify(self)
    _pickerView.completeBlock = ^(id item, NSInteger row) {
        @strongify(self)
        
        self.triggerModeLabel.text = item[@"title"];
        [[NSUserDefaults standardUserDefaults] setValue:item[@"obj"] forKey:kISSafetyAlarmMailSendType];
    };
})
@end
